import { HttpClient, HttpEvent, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { environment } from '@env/environment';
import { NzUploadChangeParam, NzUploadFile, NzUploadXHRArgs } from 'ng-zorro-antd/upload';
import { CookieService } from 'ngx-cookie-service';

import { getBase64 } from 'src/app/utils/base64.util';

import { EditorConfig } from '../../editor/editor.config';

@Component({
  selector: 'app-discover-content',
  templateUrl: './discover-content.component.html',
  styleUrls: ['./discover-content.component.sass']
})
export class DiscoverContentComponent implements OnInit {

  /**
   * Editor Config
   */
  conf = new EditorConfig(1);

  /**
   * Editor Content
   */
  content = '';

  /**
   * List
   */
  list = [];

  fileList: NzUploadFile[] = [

  ];

  previewImage: string | undefined = '';
  previewVisible = false;

  /**
   * 自定义上传
   */
  customRequest = (info: NzUploadXHRArgs) => {
    info.headers = {
      'Content-Type': info.file.name.slice(info.file.name.lastIndexOf('.') + 1),
    };

    const formData = new FormData();
    formData.append('file', info.file as any);

    return this.http.request(new HttpRequest('POST', info.action, formData, {
      headers: new HttpHeaders(info.headers),
      reportProgress: true
    })).subscribe((event: HttpEvent<{}>) => {
      if (event.type === HttpEventType.UploadProgress) {
        if (event.total > 0) {
          (event as any).percent = event.loaded / event.total * 100;
        }
        // 处理上传进度条，必须指定 `percent` 属性来表示进度
        info.onProgress(event, info.file);
      } else if (event instanceof HttpResponse) {
        // 处理成功
        info.onSuccess(event.body, info.file, event);
      }
    }, (err) => {
      // 处理失败
      info.onError(err, info.file);
    });
  }

  constructor(private cookieService: CookieService, private http: HttpClient) { }

  ngOnInit() {
    
  }

  /**
   * 发送
   */
  send() {

  }

  /**
   * 同步属性内容
   * @param str 内容
   */
  syncContent(str): void {
    this.content = str;
    console.log(this.content);
    console.log(!!this.content);
  }

  handlePreview = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  }

  uploadChange(info: NzUploadChangeParam) {
    switch (info.type) {
      case 'success':

        break;

      case 'error':
        let fileList = [...info.fileList];

        // 1. Limit the number of uploaded files
        // Only to show two recent uploaded files, and old ones will be replaced by the new
        // fileList = fileList.slice(-2);

        // 2. Read from response and show file link
        fileList = fileList.map(file => {
          // Component will show file.url as link
          file.url = environment.ACTION_IMAGE_UPLOAD + '/' + /MD5: \w{32}/.exec(info.file.error.error.text)[0].substr(5);
          file.status = 'done';
          return file;
        });

        this.fileList = fileList;
        break;
    }
  }
}
